package models

import (
	"context"
	"encoding/json"
	"github.com/cy77cc/hioshop/global"
	"math/rand"
	"time"
)

type Category struct {
	Model
	Name       string `json:"name" gorm:"varchar(90);default:''"`
	Keywords   string `json:"keywords" gorm:"varchar(255);default:''"`
	FrontDesc  string `json:"front_desc" gorm:"varchar(255);default:''"`
	ParentId   uint   `json:"parent_id" gorm:"type:int unsigned;default:0"`
	SortOrder  uint8  `json:"sort_order" gorm:"tinyint unsigned;default:50"`
	ShowIndex  int8   `json:"show_index" gorm:"tinyint;default:0"`
	IsShow     uint8  `json:"is_show" gorm:"tinyint unsigned;default:1"`
	IconUrl    string `json:"icon_url" gorm:"varchar(255);default:''"`
	ImgUrl     string `json:"img_url" gorm:"varchar(255);default:''"`
	Level      string `json:"level" gorm:"varchar(255);default:''"`
	FrontName  string `json:"front_name" gorm:"varchar(255);default:''"`
	PHeight    int    `json:"p_height" gorm:"int;default:0"`
	IsCategory int8   `json:"is_category" gorm:"tinyint;default:0"`
	IsChannel  int8   `json:"is_channel" gorm:"tinyint;default:0"`
}

func (*Category) GetChildCategoryId(parentId int) (childIds []int, err error) {
	err = global.DB.Model(&Category{}).Select("id").Where("parent_id = ?", parentId).Find(&childIds).Error
	return
}

func (c *Category) GetCategoryWhereIn(categoryId int) (childIds []int, err error) {
	childIds, err = c.GetChildCategoryId(categoryId)
	childIds = append(childIds, categoryId)
	return
}

func (c *Category) GetCategoriesByChannel() (list []Category, err error) {
	ctx := context.Background()
	get := global.REDIS.Get(ctx, "CategoriesByChannel")
	if get.Err() != nil {
		err = global.DB.Model(&Category{}).Where("is_channel=1 and parent_id=0").Order("sort_order asc").Find(&list).Error
		data, _ := json.Marshal(list)
		rint := rand.Intn(50)
		err = global.REDIS.Set(ctx, "CategoriesByChannel", data, time.Hour+time.Second*time.Duration(rint)).Err()
		return
	}

	data, _ := get.Result()
	err = json.Unmarshal([]byte(data), &list)

	return
}

func (c *Category) GetCategories() (list []Category, err error) {
	ctx := context.Background()
	get := global.REDIS.Get(ctx, "category")
	if get.Err() != nil {
		err = global.DB.Model(&Category{}).Where("parent_id=0 and is_show=1").Order("sort_order asc").Find(&list).Error
		rint := time.Duration(rand.Intn(50))
		data, _ := json.Marshal(list)
		err = global.REDIS.Set(ctx, "category", data, time.Hour+rint).Err()
		return
	}

	data, _ := get.Result()
	err = json.Unmarshal([]byte(data), &list)

	return
}

func (c *Category) GetCategoriesById(id string) (list []Category, err error) {
	err = global.DB.Model(&Category{}).Where("id=" + id).Find(&list).Error
	return
}
